import { defineComponent, cloneVNode, VNodeChild, PropType, VNode, resolveDirective, withDirectives } from 'vue'
import { render } from '../_util/props-util'
import { Value, MenuOption } from './interface'
import { useMenu } from './utils'
import BorderLight from '../border-light'

import Icon from '../icon'

export default defineComponent({
  name: 'x-menu-item-content',
  directives: {
    [BorderLight.name]: BorderLight
  },
  props: {
    node: Object as PropType<MenuOption>,
    label: [String, Object] as PropType<string | VNodeChild>,
    value: [String, Number] as PropType<Value>,
    icon: [Object, Function] as PropType<VNodeChild | (() => VNodeChild)>,
    disabled: Boolean,
    showArrow: Boolean,
    active: Boolean,
    collapsed: Boolean
  },
  setup(props) {
    const { indentRef, menuContext } = useMenu(props)

    return () => {
      const indent = indentRef.value
      const prefixCls = 'x-menu-item-content'

      const cls = {
        [prefixCls]: true,
        [`${prefixCls}-active`]: props.active,
        [`${prefixCls}-disabled`]: props.disabled,
        [`${prefixCls}-collapsed`]: props.collapsed
      }

      const iconNode = render(props.icon) as VNode

      let vnode = (
        <div class={cls}>
          {iconNode && cloneVNode(iconNode, { class: `${prefixCls}_icon`, style: `marginLeft:-${indent}px`, role: 'none' })}
          <span class={`${prefixCls}_label`}>{props.label}</span>
          {props.showArrow && <Icon class={`${prefixCls}_arrow`} type='arrow-down' />}
        </div>
      )

      // 应用 borderLight 指令
      if (menuContext.props.borderLight) {
        const dir = resolveDirective('border-light')
        const dirVal = { borderWidth: 1.2, borderGradientSize: 65, style: { opacity: 0.8 } }
        vnode = withDirectives(vnode, [[dir, dirVal]])
      }

      return vnode
    }
  }
})
